package org.boot.chat.util;

import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * 动态Bean注册工具类
 * @author: 最爱芫荽
 * @email: 15733440205@163.com
 */
@Component
public class DynamicBeanRegistry implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    /**
     * 动态注册Bean实例到Spring容器
     * @param beanName Bean名称
     * @param beanInstance Bean实例对象
     */
    public void registerSingletonBean(String beanName, Object beanInstance) {
        DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory)
                applicationContext.getAutowireCapableBeanFactory();
        beanFactory.registerSingleton(beanName, beanInstance);
    }

    /**
     * 动态注册Bean类到Spring容器（由Spring管理生命周期）
     * @param beanName Bean名称
     * @param beanClass Bean类类型
     */
    public void registerBeanDefinition(String beanName, Class<?> beanClass) {
        DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory)
                applicationContext.getAutowireCapableBeanFactory();
        RootBeanDefinition beanDefinition = new RootBeanDefinition(beanClass);
        beanFactory.registerBeanDefinition(beanName, beanDefinition);
    }

    /**
     * 从Spring容器中移除Bean
     * @param beanName Bean名称
     */
    public void removeBean(String beanName) {
        DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory)
                applicationContext.getAutowireCapableBeanFactory();
        beanFactory.removeBeanDefinition(beanName);
    }
}